﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using School.Entities;
using System.Drawing;

namespace School.Pages.Uniforms
{
    public partial class ClothesType : System.Web.UI.Page
    {
        private SchoolEntities db = new SchoolEntities();
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((IQueryable<int>)Session["privilage"] != null)
            {
                var x = (IQueryable<int>)Session["privilage"];

                if (x.Contains(1402) == true)
                {
                    if (this.Page.IsPostBack)
                    {
                        DropDownList ddl = ((DropDownList)(CampusPackage1.FindControl("ddlGrade")));
                        ddl.AutoPostBack = true;
                        ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
                        // FillControls();
                        lblResult.Text = "";
                        lblSizesMsg.Text = "";
                    }
                }
                else
                    Response.Redirect("../organization/no_privelege.aspx");
            }
            else
                Response.Redirect("../organization/no_privelege.aspx");
        }

        void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillControls();
        }
        public void FillControls()
        {
            if (CampusPackage1.CampusId != "0" && CampusPackage1.CertificateId != "0" &&
                CampusPackage1.StageId != "0" && CampusPackage1.GradeId != "0")
            {
                GridView1.DataSource = School.Service.Clothes.SRV_CLothe.getAllGrd(long.Parse(CampusPackage1.CampusId), long.Parse(CampusPackage1.CertificateId)
                    , long.Parse(CampusPackage1.StageId), long.Parse(CampusPackage1.GradeId));
                GridView1.DataBind();
            }
        }
        private void ClearForm()
        {
            txtCode.Text = "";
            txtDescrptioin.Text = "";
            txtName.Text = "";
            txtSize.Text = "";
            lstbxSizes.Items.Clear();
            btnSaveStation.Text = "اضافه";
        }

        protected void btnAddSize_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtSize.Text))
            {
                foreach (SRV_Clothe_Sizes sizeItem in db.SRV_Clothe_Sizes)
                {
                    if (sizeItem.Size_Code.Trim() == txtSize.Text.Trim())
                    {
                        lblSizesMsg.ForeColor = Color.Red;
                        lblSizesMsg.Text = " كود المقاس تم ادخاله من قبل";
                        return;
                    }
                }
                foreach (ListItem item in lstbxSizes.Items)
                {
                    if (item.Value == txtSizeCode.Text)
                    {
                        lblSizesMsg.ForeColor = Color.Red;
                        lblSizesMsg.Text = " كود المقاس تم ادخاله من قبل";
                        return;
                    }
                }
              
                lstbxSizes.Items.Add(new ListItem(txtSize.Text,txtSizeCode.Text));
                txtSize.Text = "";
                txtSizeCode.Text = "";
            }
        }

       protected void btnDeletSize_Click(object sender, EventArgs e)
       {
           if (lstbxSizes.SelectedItem != null)
               lstbxSizes.Items.Remove(lstbxSizes.SelectedItem);
       }

       protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
       {
           if (e.CommandSource is System.Web.UI.WebControls.GridView)
           {}
           else
           {
               GridViewRow selectedRow = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
               DataKey ClotheId = GridView1.DataKeys[selectedRow.RowIndex];
               if (e.CommandName == "DoEdit")
               {
                   FillForm(int.Parse(ClotheId.Value.ToString()));
                   btnSaveStation.Text = "حفظ";
                   HFClotheId.Value = ClotheId.Value.ToString();
               }
               else if (e.CommandName == "DoDelete")
               {
                   if (School.Service.Clothes.SRV_CLothe.ClotheDelete(long.Parse(ClotheId.Value.ToString())))
                   {
                       FillControls();
                       lblResult.ForeColor = Color.Green;
                       lblResult.Text = "تمت عمليه الحذف بنجاح ";
                       lblResult.Visible = true;
                       ClearForm();
                   }
               }
           }
       }

       private void FillForm(int id)
       {
           SRV_Clothe MYClothe = School.Service.Clothes.SRV_CLothe.GetById(id).First();
           txtCode.Text = MYClothe.Code;
           txtDescrptioin.Text = MYClothe.Description;
           txtName.Text = MYClothe.Name;
           CampusPackage1.CampusId = MYClothe.Campus_Id.ToString();
           if (MYClothe.Cer_Id != null)
               CampusPackage1.CertificateId = MYClothe.Cer_Id.ToString();
           if (MYClothe.Stage_Id != null)
               CampusPackage1.StageId = MYClothe.Stage_Id.ToString();
           if (MYClothe.Grad_Id != null)
               CampusPackage1.GradeId = MYClothe.Grad_Id.ToString();
           lstbxSizes.Items.Clear();
           foreach (SRV_Clothe_Sizes item in School.Service.Clothes.SRV_Clothe_Sizes_Size.AllClothesSizes().Where(s => s.Clothe_Id == id))
           {
               lstbxSizes.Items.Add(new ListItem(item.Name, item.Size_Id.ToString()));
           }
       }

       protected void btnSaveStation_Click(object sender, EventArgs e)
       {
           if (CampusPackage1.CampusId != "0" )
           {
               if (lstbxSizes.Items.Count < 1)
               {
                   lblResult.ForeColor = Color.Red;
                   lblResult.Text = "يجب ادخال قيم مقاس ";
                   return;
               }
               long? Cer_Id = null;
               if (long.Parse(CampusPackage1.CertificateId) != 0)
                   Cer_Id = long.Parse(CampusPackage1.CertificateId);
               long? grade_id = null;
               if (long.Parse(CampusPackage1.GradeId) != 0)
                   grade_id = long.Parse(CampusPackage1.GradeId);
               long? StageId = null;
               if (long.Parse(CampusPackage1.GradeId) != 0)
                   StageId = long.Parse(CampusPackage1.StageId);
               if (btnSaveStation.Text == "حفظ" && !string.IsNullOrEmpty(HFClotheId.Value))
               {
                   if (School.Service.Clothes.SRV_CLothe.ClothesUpdate(new SRV_Clothe()
                   {
                       Id = long.Parse(HFClotheId.Value),
                       Name = txtName.Text,
                       Description = txtDescrptioin.Text,
                       Code = txtCode.Text,
                       Campus_Id = long.Parse(CampusPackage1.CampusId),
                       Cer_Id = Cer_Id,
                       Grad_Id = grade_id,
                       Stage_Id = StageId
                   }))
                   {
                       List<SRV_Clothe_Sizes> lists = new List<SRV_Clothe_Sizes>();
                       foreach (ListItem item in lstbxSizes.Items)
                       {
                           lists.Add(new SRV_Clothe_Sizes() { Name = item.Text, Size_Code = item.Value, Clothe_Id = long.Parse(HFClotheId.Value), QTY = 0 });
                       }
                       if (School.Service.Clothes.SRV_Clothe_Sizes_Size.ClotheSizeAddRange(lists))
                       {
                           lblResult.ForeColor = Color.Green;
                           lblResult.Text = "تم التعديل بنجاح";
                           FillControls();
                           ClearForm();
                       }
                   }
               }
               else
               {
                   foreach (SRV_Clothe item in db.SRV_Clothe)
                   {
                       if (item.Code.TrimEnd() == txtCode.Text.TrimEnd())
                       {
                           lblResult.ForeColor = Color.Red;
                           lblResult.Text = " كود الزى تم ادخاله من قبل";
                           return;
                       }
                   }
                   List<SRV_Clothe_Sizes> listSizes = new List<SRV_Clothe_Sizes>();
                   long clotheid = 0;
                   if (School.Service.Clothes.SRV_CLothe.ClothesInsert(new SRV_Clothe()
                   {
                       Campus_Id = long.Parse(CampusPackage1.CampusId),
                       Code = txtCode.Text,
                       Description = txtDescrptioin.Text,
                       Name = txtName.Text,
                       Cer_Id = Cer_Id,
                       Grad_Id = grade_id,
                       Stage_Id = StageId

                   }, out clotheid))
                   {
                       foreach (ListItem item in lstbxSizes.Items)
                       {
                           listSizes.Add(new SRV_Clothe_Sizes() { Clothe_Id = clotheid, Size_Code = item.Value, Name = item.Text, QTY = 0 });
                       }
                       if (School.Service.Clothes.SRV_Clothe_Sizes_Size.ClotheSizeAddRange(listSizes))
                       {
                           lblResult.ForeColor = Color.Green;
                           lblResult.Text = "لقد تمت عمليه الاضافه بنجاح";
                           lblResult.Visible = true;
                           FillControls();
                           ClearForm();
                       }
                       else
                       {
                           lblResult.ForeColor = Color.Red;
                           lblResult.Text = "لم تتم عمليه الاضافه بنجاح من فضلك تاكد من القيم المدخله";
                           lblResult.Visible = true;
                           db.DeleteObject(db.SRV_Clothe.OrderByDescending(s => s.Id).FirstOrDefault());
                           db.SaveChanges();
                           FillControls();
                       }

                   }
               }
           }
       }

       protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
       {
           GridView1.PageIndex = e.NewPageIndex;
           FillControls();
       }
    }
}